package com.example.exceldemo.read;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.example.exceldemo.entity.UserExcel;
import com.example.exceldemo.mapper.UserMapper;
import com.example.exceldemo.service.UserService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yanhongwei
 * @Date: 2023/07/13 17:27:16
 * @Description: TODO 批量导入数据
 */

@Slf4j
public class BasicExcelListener extends AnalysisEventListener<UserExcel> {
    private UserService userService;

    public BasicExcelListener() {
    }

    public BasicExcelListener(UserService userService) {
        this.userService = userService;
    }

    /*** 批处理阈值2000*/
    private static final int BATCH_COUNT = 2000;
    List<UserExcel> list = new ArrayList<>();

    @Override
    public void invoke(UserExcel basic, AnalysisContext analysisContext) {
        //获取对应的行数
        int num = analysisContext.readRowHolder().getRowIndex();
//        basic.setRowNum(num + 1);
        list.add(basic);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        //调用saveData()方法
        userService.saveBatch(list);
    }
}
